<template>
  <div>
     <h1>京东搜索</h1>
     <div class="search_wrap">
      <input v-model.trim="searchText" type="text" @input="getSearch">
      <div class="btn">搜索</div>
      <div class="search_result" v-if="searchList.length!=0">
        <div class="result_one" v-for="item in searchList" :key="item.xsd">

          <span style="color:red;">{{searchText}}</span>
           <span >{{item.sp.substr(searchTrim.length)}}</span>
        </div>
      </div>
     </div>
  </div>
</template>
<script>
export default {
  name:"cart",
  data(){
    return {
      searchText:"",//收集输入框输入的搜索内容
      searchList:[]//返回的搜索数据
    }
  },
  computed:{
    searchTrim(){ //把搜索字段去除空格
      return this.searchText.replace(/\s*/g,"")
    }
  },
  methods:{ 
    getSearch(){ //实时输入事件调用接口
      this.$axios({
        url:"/api/taobao-lx/",
        method:"get",
        params:{
          msg:this.searchText //传送搜索数据给后台
        }
      }).then(res=>{
        if(res.data.code==-1){
           console.log("没有数据")
           this.searchList=[];//清空数据
        }else{
           console.log("有数据")
           let str=res.data; //存储后台返回的字符串
          //  将字符串不标准的，] 换成 ]
           let strResult=str.replace(/,\]/g,"]")
          // 使用JSON.parse转换数据
           this.searchList=JSON.parse(strResult).data
           console.log( this.searchList,"---")
           
        }
      })

    }
  }
}
</script>
<style lang="scss" scoped>
   .search_wrap{
    width: 600px;
    height: 70px;
    margin: 0 auto;
    display: flex;
    position: relative;
    input{
      width: 500px;
    }
    .btn{
      width: 100px;
      height: 70px;
      background: red;
      color: #fff;
      text-align: center;
      line-height: 70px;
    }
   }
   .search_result{
    width: 600px;
    margin: 0 auto;
    position: absolute;
    border: 1px solid black;
  
    top:70px;
    left:0;
    .result_one{
      height: 50px;
      line-height: 50px;
      border-bottom: 1px solid #ccc;
    }
   }
</style>